package com.ylyq.ylxx.util;

import com.ylyq.ylxx.constants.ShiroConstant;
import com.ylyq.ylxx.model.UserToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtils {
    public static String generateToken(UserToken userToken, int expire, String jwtPrivateKey) throws Exception {
        String token = Jwts.builder()
                .setSubject(userToken.getUserId())
                .claim(ShiroConstant.CONTEXT_USER_ID, userToken.getUserId())
                .claim(ShiroConstant.CONTEXT_USER_NAME, userToken.getUsername())
                .claim(ShiroConstant.RENEWAL_TIME,new Date(System.currentTimeMillis()+expire/2))
                .setExpiration(new Date(System.currentTimeMillis()+expire))
                .signWith(SignatureAlgorithm.HS256, jwtPrivateKey)
                .compact();
        return token;
    }


    public static UserToken getInfoFromToken(String token, String jwtPrivateKey){
        Claims claims = Jwts.parser()
                .setSigningKey(jwtPrivateKey).parseClaimsJws(token)
                .getBody();
        return new UserToken(claims.get(ShiroConstant.CONTEXT_USER_ID).toString(),claims.get(ShiroConstant.CONTEXT_USER_NAME).toString());
    }
}
